<template>
  <form class="w-50 m-auto mt-5">
    <div class="mb-3">
      <label for="field1" class="form-label">Имя пользователя</label>
      <input
        type="text"
        :class="'form-control ' + get_msg_class('name')"
        id="field1"
        aria-describedby="emailHelp"
        v-model="name"
      />
      <div class="invalid-feedback">
        {{ get_msg("name") }}
      </div>
    </div>
    <div class="mb-3">
      <label for="field3" class="form-label">email</label>
      <input
        type="email"
        :class="'form-control ' + get_msg_class('email')"
        v-model="email"
        id="field3"
      />
      <div class="invalid-feedback">
        {{ get_msg("email") }}
      </div>
    </div>
    <div class="mb-3">
      <label for="field2" class="form-label">Пароль</label>
      <input
        type="password"
        :class="'form-control ' + get_msg_class('password')"
        v-model="password"
        id="field2"
      />
      <div class="invalid-feedback">
        {{ get_msg("password") }}
      </div>
    </div>
    <div class="mb-3">
      <label for="field4" class="form-label">Наименование организации или ИНН</label>
      <input
        type="text"
        :class="'form-control ' + get_msg_class('organization')"
        v-model="organization"
        id="field4"
        list="organizations"
      />
      <datalist id="organizations" data-size="10">
        <option v-for="item in autocomplete" :key="item.name" :value="item.name"></option>
      </datalist>
      <div class="invalid-feedback">
        {{ get_msg("organization") }}
      </div>
    </div>
    <button type="button" class="btn btn-primary" @click="sendForm()">
      Отправить
    </button>
    <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
  </form>
</template>
  
  <script>
import { useFetch } from "@vueuse/core";
import VueBasicAlert from "vue-basic-alert";

export default {
  props: {
    tokens: Object,
    user: Object,
  },
  components: { VueBasicAlert },
  data() {
    return {
      name: "",
      password: "",
      organization: "",
      email: "",
      detail: [],
      autocomplete: [],
    };
  },
  watch: {
    organization() {
      this.get_autocomplete();
    },
  },
  methods: {
    get_autocomplete() {
      this.autocomplete = [];
      const { data, onFetchError, onFetchResponse } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/organization/autocomplete?name=${this.organization}`
      ).get();

      onFetchError((error) => {
        this.error += error.message;
      });

      onFetchResponse(() => {
        this.autocomplete = JSON.parse(data.value);
      });
    },
    get_msg_class(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = "is-invalid";
        }
      });
      return ans;
    },
    get_msg(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = el.msg;
        }
      });
      return ans;
    },
    sendForm() {
      this.detail = [];
      fetch(`${process.env.VUE_APP_BASE_URI}/signup`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: this.name,
          password: this.password,
          organization: this.organization,
          email: this.email,
        }),
      }).then(
        (resp) => {
          if (resp.status != 500) {
            resp.json().then(
              (body) => {
                if (resp.ok) {
                  this.detail = [];
                  // Редирект на главную
                  this.name = "";
                  this.password = "";
                  this.organization = "";
                  this.email = "";
                  this.$refs.alert.showAlert(
                    "success",
                    `На вашу почту выслали письмо подтверждения`,
                    "Успех"
                  );
                  // this.$router.push("/login");
                } else {
                  this.$refs.alert.showAlert(
                    "error",
                    `${resp.statusText}`,
                    "Ошибка"
                  );
                }
                if (resp.status == 422) {
                  this.detail = body.detail;
                }
              },
              () => {
                this.$refs.alert.showAlert(
                  "error",
                  "Ошибка сервера",
                  "Ошибка обработки json"
                );
              }
            );
          } else {
            this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
          }
        },
        (err) => {
          this.$refs.alert.showAlert("error", "Ошибка сервера", err.message);
        }
      );
    },
  },
};
</script>
  
  <style>
</style>